<template>
    <div class="page flex-col">
        <div class="group_1 flex-row">
            <div class="box_1 flex-col"></div>
        </div>
        <div class="group_2 flex-row">
            <div class="box_2 flex-col"></div>
        </div>
        <div class="group_3 flex-row">
            <div class="group_4 flex-col"></div>
        </div>
        <div class="group_5 flex-row">
            <div class="group_6 flex-col"></div>
        </div>
        <div class="group_7 flex-row">
            <div class="box_3 flex-col"></div>
        </div>
        <div class="group_8 flex-row">
            <div class="group_9 flex-col"></div>
        </div>
        <div class="group_10 flex-col justify-end">
            <div class="block_1 flex-row">
                <span class="text_1">欢迎来到康康后台</span>
                <div class="block_2 flex-col justify-between">
                    <div class="box_4 flex-col"></div>
                    <div class="box_5 flex-col"></div>
                    <div class="box_6 flex-col"></div>
                </div>
                <img class="image_1" referrerpolicy="no-referrer"
                    src="https://lanhu.oss-cn-beijing.aliyuncs.com/FigmaDDSSlicePNGb45467756a5436a85565e24e2b84b5ac.png" />
            </div>
            <div class="block_3 flex-row justify-between">
                <div class="box_7 flex-col"></div>
                <div class="box_8 flex-col"></div>
            </div>
            <div class="block_4 flex-row">
                <span class="text_2">IN</span>
                <div class="group_11 flex-col"></div>
                <div class="group_12 flex-col"></div>
            </div>
            <div class="image-wrapper_1 flex-row">
                <img class="image_2" referrerpolicy="no-referrer"
                    src="https://lanhu.oss-cn-beijing.aliyuncs.com/FigmaDDSSlicePNGa6b06a9f94d05a99273bc374f49aa6b8.png" />
            </div>
            <div class="block_5 flex-row justify-between">
                <span class="text_5">SIGN</span>
            </div>
        </div>

        <div class="contents">
            <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 30 }" autocomplete="off"
                @finish="onFinish" @finishFailed="onFinishFailed" class="forms" ref="forms" :rules="loginFormRules">
                <a-form-item name="username">
                    <a-input v-model:value="formState.username" class="inputs" autocomplete="new-password" id="ones"
                        :bordered="false" placeholder="username" />
                </a-form-item>

                <a-form-item name="password">
                    <a-input-password v-model:value="formState.password" autocomplete="new-password" :bordered="false"
                        id="ko" class="inputs" placeholder="password" />
                </a-form-item>
                <a-form-item name="code" v-if="codeData.length == 2">
                    <a-input v-model:value="formState.code" autocomplete="new-password" :bordered="false" class="inputs"
                        placeholder="code" />
                    <img class="codeImg" @click="changeCode" :src="'data:image/png;base64,' + codeData[1]" alt="">
                </a-form-item>
                <a-form-item>
                    <div class="btsBox">
                        <a-button type="primary" html-type="submit" class="btns">登录</a-button>
                        <a-button type="primary" class="reset btns" @click="resets">重置</a-button>
                    </div>
                </a-form-item>
            </a-form>
        </div>
    </div>
</template>


<script setup>
import { reactive, ref, onMounted } from 'vue';
import { loginAPI } from '../../api/login'
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { MD5 } from "crypto-js";
import share from '../../util/commnet'
import { useUserData } from '../../stores/userData'
import { debounce } from 'lodash'

const router = useRouter();
// 表单数据
const formState = reactive({
    username: '',
    password: '',
    code: '',
    remember: true,
});

// 表单ref
const forms = ref('')



// 用户信息保存
const store = useUserData();

// 验证码操作------------------------------
const validateIdentifyCode = (rule, value) => {

    if (value.toUpperCase() !== code.value) {
        forms.value.code = "";
        return Promise.reject('验证码错误');

    } else {
        return Promise.resolve()
    }
};

//验证规则
const loginFormRules = {
    username: [{ required: true, message: "请输入用户名" }],
    password: [{ required: true, message: "请输入密码" }],
    code: [
        { required: true, validator: validateIdentifyCode, trigger: "blur" },
    ],
}





// 当通过验证
const onFinish = async values => {
    const uuid = codeData.value[0]?.length > 0 ? codeData?.value[0] : share.uuidADD();
    formState.password = MD5(formState.password).toString();

    const data = `login|${formState.username}|${formState.password}|${uuid}|${codeData.value ? code.value : ''}`;
    console.log(`login|${formState.username}|${formState.password}|${uuid}|${codeData.value ? code.value : ''}`);
    let res = await loginAPI(data);
    console.log(res);
    if (res.code != 200 || !res) {   //身份验证失败
        message.error(res.message, 2);
        forms.value.resetFields();
        if (res?.url) {           // 如果是密码错误登录失败        返回验证码 [base64,code]

            codeData.value = [uuid, res.url[0]];

            code.value = res.url[1];

            localStorage.setItem('codeData', codeData.value.join('@@@'))
        }
        return;

    }
    //成功登录
    message.success(res.message, 1);
    store.data = res.data;
    store.data.keyArray = share.generateNewArray(share.treeData, store.data.file);
    router.replace({ name: 'admin' })
};
// 验证表单错误
const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
};

// 重置表单
const resets = () => {
    forms.value.resetFields()
}


//验证码操作
const codeData = ref([]);
const code = ref('');



// 防抖处理的函数
const debouncedChangeCode = debounce(async () => {
    let res = await loginAPI(`set|${codeData.value[0]}`);

    if (res.code == 400) {
        message.error("刷新失败");
    } else {
        message.success("刷新验证码成功");
        codeData.value = [res.test, res.data[0]];
        code.value = res.data[1];
        localStorage.setItem('codeData', codeData.value.join('@@@'));
    }
}, 200); // 设置防抖延迟时间（单位：毫秒）


const changeCode = async () => {  //点击更换验证码 防抖200ms
    debouncedChangeCode()
}

onMounted(async () => {

    if (localStorage.getItem('codeData')?.split('@@@').length == 2) {  //当存在uuid和验证码时时

        let res = await loginAPI(`code|${localStorage.getItem('codeData')?.split('@@@')[0]}`);

        if (res?.data != false) {
            codeData.value = localStorage.getItem('codeData').split('@@@');
            code.value = res.data.code;

        } else {
            localStorage.setItem('codeData', '');   //数据库不存在数据 删除本地记录
        }
    }
})



</script>



<style  src="../css/login.scss"></style>
<style scoped src="../css/com.css"></style>

<style scoped>
.codeImg {
    position: absolute;
    right: 0vw;
    top: 2vh;
    cursor: pointer;
    width: 6vw;
    height: 4vh;
}
</style>